<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>新增微信模板消息</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
    <style>
        .mainBox {
            padding: 15px;
        }

        .main-container {
            max-width: 850px;
            margin: 0 auto;
        }

        .layui-form-item {
            margin-bottom: 22px;
        }

        .form-tip {
            display: block;
            margin-top: 8px;
            color: #666;
            font-size: 12px;
            line-height: 1.5;
        }

        .form-tip i {
            color: #1E9FFF;
            margin-right: 4px;
        }

        .json-example {
            margin-top: 8px;
            padding: 10px;
            background: #f8f8f8;
            border-radius: 4px;
            border: 1px solid #eee;
            font-family: monospace;
            font-size: 12px;
            color: #333;
            white-space: pre-wrap;
            word-break: break-all;
        }

        .bottom {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px;
            background: #fff;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
            z-index: 99;
        }

        .button-container {
            text-align: center;
        }

        .button-container button {
            margin: 0 10px;
        }
    </style>
</head>

<body>
    <form class="layui-form" action="" lay-filter="wechat-template-add">
        <div class="mainBox">
            <div class="main-container">
                <!-- 模板标题（唯一，必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">模板标题 <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="name" lay-verify="required|verifyName|verifyNameUnique"
                            autocomplete="off" placeholder="请输入模板标题（如：订单支付成功通知）" class="layui-input">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>
                            标题为唯一标识，不可重复；建议清晰描述用途，便于管理
                        </span>
                    </div>
                </div>

                <!-- WXAPPID（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">开发者ID<span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="wx_app_id" id="wx_app_id" lay-verify="required|verifyAppIdLength"
                            autocomplete="off" placeholder="输入微信公众号/小程序APPID" class="layui-input">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>
                            从微信公众平台「开发-基本配置」获取，长度18-32位
                        </span>
                    </div>
                </div>

                <!-- WXAPPSECRET（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">开发者密码&nbsp;<span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="wx_app_secret" id="wx_app_secret"
                            lay-verify="required|verifyAppSecretLength" autocomplete="off"
                            placeholder="输入微信公众号/小程序APPSECRET" class="layui-input">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-warning"></i>
                            注意保密！泄露可能导致账号安全风险
                        </span>
                    </div>
                </div>

                <!-- 微信模板ID（必填，正则验证） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">微信模板ID <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="template_id" id="template_id" lay-verify="required|verifyTemplateId"
                            autocomplete="off" placeholder="如：HzvBOeBKgqSDi_jfvyFt_O5SyP7Sv3_whbAlR7qukX0"
                            class="layui-input">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>
                            从微信公众平台「模板消息-我的模板」获取，支持10-64位字母/数字/_/-
                        </span>
                    </div>
                </div>

                <!-- 模板变量（JSON格式，非必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">模板变量</label>
                    <div class="layui-input-block">
                        <textarea name="template_data" id="template_data" lay-verify="verifyJson" autocomplete="off"
                            placeholder="输入JSON格式变量" class="layui-textarea" rows="6"></textarea>
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>
                            变量需与微信模板占位符对应（如{{first.DATA}}对应"first"）
                        </span>
<div class="json-example">
示例：
{
    "phone_number3": {"value": "18888888888"},
    "time8": {"value": "2025年10月27日 23:47:19"},
    "thing11": {"value": "绑定成功"},
    "remark": {"value": "remark"}
}</div>
                    </div>
                </div>

                <!-- 描述说明（非必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">描述说明</label>
                    <div class="layui-input-block">
                        <textarea name="description" id="description" autocomplete="off" placeholder="输入模板用途说明"
                            class="layui-textarea" rows="3"></textarea>
                    </div>
                </div>

                <!-- 模板状态（必填，默认开启） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">模板状态 <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_active" value="1" title="开启" lay-skin="tag" checked>
                        <input type="radio" name="is_active" value="0" title="关闭" lay-skin="tag">
                    </div>
                </div>

                <!-- 排序号（非必填，默认0） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">排序号</label>
                    <div class="layui-input-block">
                        <input type="text" name="sort_num" id="sort_num" lay-verify="verifySort" autocomplete="off"
                            value="0" placeholder="0-9999的非负整数" class="layui-input">
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit
                    lay-filter="wechat-template-save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交保存
                </button>
                <button type="reset" class="pear-btn pear-btn-sm" id="reset-btn">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置表单
                </button>
                <button type="button" class="pear-btn pear-btn-danger pear-btn-sm" id="close-btn">
                    <i class="layui-icon layui-icon-close"></i>
                    取消关闭
                </button>
            </div>
        </div>
    </form>

    <!-- 依赖JS -->
    <script src="../../../component/com/api.js"></script>
    <script src="../../../component/com/auth.js"></script>
    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script>
        layui.use(['form', 'jquery', 'layer'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let layer = layui.layer;

            // 1. 全局配置
            const API_BASE_URL = apiConfig.baseUrl;
            const AUTH_TOKEN = window.localStorage.getItem("token") || window.sessionStorage.getItem("token");
            const ADD_API_URL = `${API_BASE_URL}/wechat/template/`; // 新增接口

            // 2. 表单验证规则
            form.verify({
                // 模板标题：1-20位，支持常用字符
                verifyName: function (value) {
                    const trimVal = value.trim();
                    if (!trimVal) return "模板标题不能为空";
                },

                // WXAPPID长度验证
                verifyAppIdLength: function (value) {
                    const trimVal = value.trim();
                    if (trimVal.length < 18 || trimVal.length > 32) {
                        return "APPID长度应为18-32位";
                    }
                },
                // WXAPPSECRET长度验证
                verifyAppSecretLength: function (value) {
                    const trimVal = value.trim();
                    if (trimVal.length < 32 || trimVal.length > 64) {
                        return "APPSECRET长度应为32-64位";
                    }
                },
                // 模板ID正则验证
                verifyTemplateId: function (value) {
                    const trimVal = value.trim();
                    const reg = /^[a-zA-Z0-9_\-]{10,64}$/;
                    if (!reg.test(trimVal)) {
                        return "模板ID需为10-64位字母/数字/_/-";
                    }
                },
                // JSON格式验证
                verifyJson: function (value) {
                    const trimVal = value.trim();
                    try {
                        const jsonData = JSON.parse(trimVal);
                        // 校验是否为非空对象
                        if (typeof jsonData !== 'object' || jsonData === null || Object.keys(jsonData).length === 0) {
                            return "模板变量需为非空JSON对象,JSON格式错误，请参考示例调整";
                        }
                    } catch (e) {
                        return "模板变量格式错误，请输入标准JSON（参考示例）";
                    }
                },
                // 排序号：0-9999非负整数
                verifySort: function (value) {
                    const num = parseInt(value);
                    if (isNaN(num) || num < 0 || num > 9999) {
                        return "排序号需为0-9999的非负整数";
                    }
                }
            });

            // 3. 表单提交事件
            form.on('submit(wechat-template-save)', function (data) {
                const submitData = {
                    name: data.field.name.trim(),
                    wx_app_id: data.field.wx_app_id.trim(),
                    wx_app_secret: data.field.wx_app_secret.trim(),
                    template_id: data.field.template_id.trim(),
                    is_active: parseInt(data.field.is_active),
                    sort_num: parseInt(data.field.sort_num),
                    // 关键：template_data 直接保留用户输入的原始字符串（含换行）
                    template_data: data.field.template_data.trim()
                };
                // 2. 可选字段：非空才添加（避免传空字符串覆盖后端默认值）
                if (data.field.description.trim()) {
                    submitData.description = data.field.description.trim();
                }
                // 3.3 发送请求
                const loading = layer.load(2, { shade: 0.3 });
                console.log('wechat ajax post')
                $.ajax({
                    url: ADD_API_URL,
                    type: 'POST',
                    headers: {
                        "Authorization": AUTH_TOKEN,
                        "Content-Type": "application/json"
                    },
                    data: JSON.stringify(submitData),
                    dataType: 'json',
                    success: function (result) {
                        console.log('wechat ajax post recv = ', result)
                        layer.close(loading);
                        if (result.success) {
                            layer.msg(result.message || "新增成功", {
                                icon: 1,
                                time: 1500
                            }, function () {
                                // 关闭弹窗并刷新父页面表格
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                                parent.layui.table.reload("base-table");
                            });
                        } else {
                            // 处理后端错误提示
                            let errMsg = result.message || "新增失败";
                            if (result.data && typeof result.data === 'object') {
                                const firstErr = Object.values(result.data)[0];
                                errMsg = firstErr ? firstErr[0] : errMsg;
                            }
                            layer.msg(errMsg, { icon: 2, time: 2000 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loading);
                        const errMsg = xhr.status === 401 ? "登录过期，请重新登录" : "网络异常，新增失败";
                        layer.msg(errMsg, { icon: 2, time: 2000 });
                        if (xhr.status === 401) parent.window.location.href = '../../../login.html';
                    }
                });

                return false; // 阻止默认提交
            });

            // 4. 重置按钮事件（重置后重新渲染表单）
            $('#reset-btn').on('click', function () {
                setTimeout(() => {
                    form.render(); // 重新渲染单选框等组件
                }, 100);
                layer.msg("表单已重置", { icon: 0, time: 1000 });
            });

            // 5. 关闭按钮事件
            $('#close-btn').on('click', function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

            // 6. 页面加载完成后初始化表单渲染
            $(function () {
                form.render();
            });
        });
    </script>
</body>

</html>